package com.xjh.serverinspect.security;

import com.alibaba.fastjson2.JSON;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

/**
 * <p>
 * 响应体处理器
 * </p>
 *
 * @author xujinghui
 * @since 2024-12-13
 */
public class ResponseBodyHandler {

    private static final String PRIVATE_KEY;

    static {
        try {
            InputStream inputStream = new ClassPathResource("RSAPrivateKey").getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            PRIVATE_KEY = bufferedReader.readLine();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static Object encrypt(Object data, ServerHttpRequest req) {
        List<String> headers = req.getHeaders().get("X-Encrypt");

        if (headers != null && !headers.isEmpty()) {
            String encodeAesKey = headers.get(0);
            try {
                String aesKey = RSAUtils.decryptByPrivateKey(encodeAesKey, PRIVATE_KEY);
                return AESUtils.encrypt(JSON.toJSONString(data), aesKey);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return data;
    }

    public static Object encrypt(Object data, HttpServletRequest req) {
        String encodeAesKey = req.getHeader("X-Encrypt");

        if (StringUtils.hasText(encodeAesKey)) {
            try {
                String aesKey = RSAUtils.decryptByPrivateKey(encodeAesKey, PRIVATE_KEY);
                return AESUtils.encrypt(JSON.toJSONString(data), aesKey);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return data;
    }

}
